package com.face.server.controller;

import com.face.RespMsg;
import com.face.server.entity.Admin;
import com.face.server.entity.Bulletin;
import com.face.server.repository.BulletinRepository;
import com.util.DateUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.Arrays;

/**
 * @author jsh
 */
@RestController
@RequestMapping("bulletin")
public class BulletinController {

    @Autowired
    BulletinRepository bulletinRepository;

    @GetMapping
    RespMsg findAll(@PageableDefault(size = 10000) Pageable pageable,
                    @RequestParam(defaultValue = "0000-00-00") String begin,
                    @RequestParam(defaultValue = "9999-99-99") String end,
                    @RequestParam(defaultValue = "") String input) throws ParseException {
        return RespMsg.build(bulletinRepository.findBy(DateUtils.parse(begin), DateUtils.parse(end), input, pageable));
    }

    @GetMapping("build")
    RespMsg findByBuildNum(int build) {
        if (build == 0) {
            return RespMsg.build(bulletinRepository.findAll());
        }
        return RespMsg.build(bulletinRepository.findBySendToContains(build));
    }

    @PostMapping("save")
    RespMsg save(@RequestBody Bulletin bulletin) {
        Subject subject = SecurityUtils.getSubject();
        Admin admin = (Admin) subject.getPrincipal();
        bulletin.setAdminName(admin.getName());
        return RespMsg.build(bulletinRepository.save(bulletin).getId());
    }

    @DeleteMapping
    RespMsg delete(String[] id) {
        bulletinRepository.deleteByIdIn(Arrays.asList(id));
        return RespMsg.build("删除成功");
    }
}
